<route lang="json5">
  {
    style: {
      navigationStyle: 'custom',
      navigationBarTitleText: '申请成为合伙人',
    },
  }
</route>
  
<template>
  <view class="bg-white" :class="[{ 'dark-color': themeConfig.theme === 'dark' }]">
    <wd-form ref="formRefs" :model="formData" :errorType="errorType">
      <wd-input 
        align-right 
        type="text" 
        label="姓名或昵称" 
        prop="name"
        v-model="formData.name" 
        placeholder="请输入姓名或昵称" 
        :rules="[{ required: true, message: '请输入姓名或昵称！' }]"
      />
      <view class="border-1px"></view>
      
      <wd-input 
        align-right 
        type="text" 
        label="手机号" 
        prop="phoneNumber"
        v-model="formData.phoneNumber" 
        placeholder="请输入手机号" 
        :rules="[{ required: true, message: '请输入手机号！' }]"
      />
      <view class="border-1px"></view>
      
      <wd-picker 
        v-if="pageType === 'partner' && partnerList.length"
        align-right 
        :columns="partnerList" 
        label="合伙人类型" 
        v-model="formData.partnerType" 
        prop="partnerType"
        :rules="[{ required: true, message: '请选择合伙人类型！' }]"
      />
      <view class="border-1px" v-if="pageType === 'partner' && partnerList.length"></view>
      
      <wd-cell 
        v-if="pageType === 'partner'"
        title="是否单身" 
        required 
      >
        <view class="flex flex-row-reverse">
          <wd-switch v-model="formData.singleFlag" :size="20" />
        </view>
      </wd-cell>
      <view class="border-1px" v-if="pageType === 'partner'"></view>
      
      <wd-cell 
        title="所在区域" 
        required 
        :value="city ? city : '请选择'" 
        :custom-value-class="city ? '' : 'cell-placeholder'"
        is-link 
        :to="`/feature/areaPicker?isAll=1&isRequired=2&areaStr=${[formData.provinceId,formData.cityId,formData.districtId].filter(item => !!item).join(',')}`"
      ></wd-cell>
      <view class="border-1px"></view>
      
      <view class="w-750rpx m-a pl-32rpx pr-32rpx box-border font-size-28rpx pt-20rpx">
        <text class="font-size-15px color-#fa4350">*</text>
        {{ pageType == 'partner' ? '备注' : '需求描述' }}
      </view>
      <view class="w-center !mt-20rpx">
        <wd-textarea 
          placeholderStyle="font-size: 28rpx" 
          v-model="formData.demandDescription" 
          :placeholder="msg" 
          prop="demandDescription"
          :rules="[{ required: true, message: msg }]"
        />
      </view>
    </wd-form>
    
    <!-- 注册合伙人 -->
    <view class="btn-full w-center pt-40rpx">
      <wd-button 
        class="btn-w-full btn-h-78"
        :loading="loading"
        @click="submit"
      >确定</wd-button>
    </view>

    <view class="w-full h-78rpx"></view>
  </view>
</template>
  
<script lang="ts" setup>
import { AddOfflineServiceProviderInfo, GetPartnerCategoryConfigList, OfflineServiceProviderQueryByUserId } from '@/service/db_feature';
import { useCommonStore, useThemeStore, useUserStore } from '@/store';
import { useToast } from 'wot-design-uni';

// 主题颜色
const { themeConfig } = useThemeStore();
const common = useCommonStore();
const user = useUserStore();
const toast = useToast();

const partnerList = ref([]);
// 获取合伙人类别配置列表
const getPartnerCategoryConfigList = async() => {
  try {
    const res = await GetPartnerCategoryConfigList({});
    const list = res.data || [];
    partnerList.value = list.map(item => {
      return {
        ...item,
        label: item.categoryName,
        value: item.categoryCode
      }
    })
    if (!formData.partnerType) {
      formData.partnerType = partnerType.value || providerDetail.value.partnerType;
    }
  } catch (error) {
    console.log(error)
  }
}

const formData = reactive({
  contactInfo: '',
  name: '',
  phoneNumber: '',
  demandDescription: '',

  provinceId: '',
  cityId: '',
  districtId: '',

  partnerType: '',
  singleFlag: true,
})

// 线下服务商详情
const providerDetail = ref<any>({});
const formRefs = ref();
const errorType = ref<"message" | "toast" | "none">('toast');
const submit = () => {
  let tip = '';
  if (!user.userInfo.verificationFlag) {
    tip = '请先完成实名认证';
  }
  if (tip) {
    setTimeout(() => {
      uni.navigateTo({ url: '/activity/info' });
    }, 1000)
    return toast.show(tip);
  }
  formRefs.value
    .validate()
    .then(({ valid }) => {
      if (!valid) return;
      if (!formData.provinceId) return toast.show('请选择所在区域！');
      
      const data = {
        ...formData,
        userId: user.userInfo.id,
        type: pageType.value,
        partnerType: formData.partnerType || providerDetail.value.partnerType
      }
      if (formData.partnerType && formData.partnerType !== providerDetail.value.partnerType) {
        common.reduceMoney({
          userId: user.userInfo.id,
          type: 'partner',
          relatedBusinessInfo: JSON.stringify(data),
        }, () => {
          toast.show('支付成功!');
          user.loginSubmit = true;

          setTimeout(() => {
            uni.navigateBack();
          }, 1000);
        })
      } else {
        addOfflineServiceProviderInfo(data);
      }
    })
    .catch((error) => {
      console.log(error, 'error')
    })
}

const loading = ref(false);
// 申请线下服务商
const addOfflineServiceProviderInfo = async(data) => {
  try {
    loading.value = true;
    const res = await AddOfflineServiceProviderInfo(data);
    loading.value = false;
    if (res.code != 200) {
      return toast.show(res.message);
    }
    toast.show('操作成功!');
    user.loginSubmit = true;

    setTimeout(() => {
      uni.navigateBack();
    }, 1000);
  } catch (error) {
    loading.value = false;
    console.log(error)
  }
}

// 回填信息
const backfill = (data) => {
  for (const key in formData) {
    if (key === 'singleFlag') {
      formData[key] = !!data[key];
      continue;
    }
    if (key === 'phoneNumber') {
      formData[key] = data[key] ? data[key] : user.userInfo.phone;
      continue;
    }
    if (key === 'name') {
      const userProfileInfoVo = user.userInfo.userProfileInfoVo || {} as any;
      formData[key] = data[key] ? data[key] : userProfileInfoVo.nickname;
      continue;
    }
    formData[key] = data[key];
  }
  const { provinceName, cityName, districtName } = data || {};
  if (!provinceName) return;
  city.value = provinceName === cityName ? `${cityName}${districtName}` : `${provinceName}${cityName}${districtName}`;
}

// 根据id获取线下服务商表详情
const getOfflineServiceProvider = async () => {
  const res = await OfflineServiceProviderQueryByUserId({
    userId: user.userInfo.id,
    type: pageType.value,
  });
  const data = res.data || {};
  providerDetail.value = data;
  backfill(data);
} 

const titleType = ref(0); // 0(partner)合伙人 1(emotion)情感商学院
const pageType = ref('partner');
const msg = ref('');
const titleList = [
  '申请成为合伙人',
  '情感商学院'
]

const city = ref('');
// 更新城市
function handleUpdateArea(data) {
  if (!data) {
    city.value = '';
    Object.assign(formData, {
      provinceId: undefined, 
      cityId: undefined, 
      districtId: undefined
    })
    return
  }
  
  const [valStr, labelStr] = data.split('/');
  const [provinceVal, cityVal, districtVal] = valStr.split(',');
  const labelList = labelStr.split(',');
  
  // 如果地区名称重复, 只留一个
  if (labelList[0] === labelList[1]) {
    labelList.shift();
  }
  city.value = labelList.join('');
  Object.assign(formData, {
    provinceId: provinceVal, 
    cityId: cityVal, 
    districtId: districtVal
  })
}

const partnerType = ref('');
onLoad((options) => {
  uni.$on('updateArea', handleUpdateArea);
  const { type, categoryCode } = options || {};
  titleType.value = type;
  partnerType.value = categoryCode;
  pageType.value = type == '1' ? 'emotion' : 'partner';
  msg.value = type == '1' 
                ? '请输入想学习的内容(比如:夫妻相处、两性关系、亲子教育、婆媳关系、婚姻家庭咨询等)' 
                : '请输入合伙人相关情况（比如:姓名、性别、年龄、曾从事行业、是否有团队，有哪些资源及其他需要注明的事项。）';

  // #ifdef H5
  setTimeout(() => {
    document.title = titleList[titleType.value];
  }, 0)
  // #endif
  getOfflineServiceProvider();
})

// 页面卸载时移除监听
onUnload(() => {
  uni.$off('updateArea', handleUpdateArea);
})

onShow(() => {
  nextTick(() => {
    // 设置页面标题
    themeConfig.title = titleList[titleType.value];
    getPartnerCategoryConfigList();
  })
  if (!user.userInfo.id) {
    uni.navigateTo({
      url: '/pages/login/index'
    })
    return
  }
})
</script>

<style lang="scss" scoped>
:root,
page {
  background-color: #fff !important;
}

.textarea-com {
  font-size: 28rpx !important;
  box-sizing: border-box !important;
}

:deep(.uni-textarea-textarea) {
  @extend .textarea-com;
}

:deep(.wot-theme-light) {
  .wd-textarea__inner,
  .uni-textarea-placeholder,
  .uni-textarea-wrapper {
    @extend .textarea-com;
    background-color: #FAF7FF !important;
  }

  .wd-textarea {
    background-color: #FAF7FF !important;
  }
}

:deep(.wot-theme-dark) {
  .wd-textarea,
  .uni-textarea-placeholder,
  .uni-textarea-wrapper {
    background-color: #141414 !important;
  }
}

:deep(.wd-input) {
  padding-right: 44rpx !important;
}

// 覆盖 wd-slider 样式 start
:deep(.wd-slider__label),
:deep(.wd-slider__label-min),
:deep(.wd-slider__label-max) {
  display: none
}
:deep(.wd-slider) {
  padding-top: 26rpx;

  .wd-slider__button {
    border: 3rpx solid #986DF0;
  }
}
// 覆盖 wd-slider 样式 end

:deep(.wd-cell__right) {
  flex: 2 !important;
}
:deep(.cell-placeholder) {
  color: #bfbfbf;
}
</style>
    